"""
简单的配置管理 - 使用环境变量和 .env 文件
"""

import os
from dotenv import load_dotenv

# 加载 .env 文件
load_dotenv()

# 数据库配置
MYSQL_DB_URL = os.getenv("MYSQL_DB_URL", "mysql+pymysql://root:root@localhost:3306/sakila")
MILVUS_HOST = os.getenv("MILVUS_HOST", "localhost")
MILVUS_PORT = int(os.getenv("MILVUS_PORT", "19530"))

# OpenAI 配置
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "sk-zk27b33f9750ab4d8b68c9d2482791ebe9c6670387cf12d2")
OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.zhizengzeng.com/v1")
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "o4-mini")
OPENAI_EMBEDDING_MODEL = os.getenv("OPENAI_EMBEDDING_MODEL", "text-embedding-3-large")

# Agent 配置
AGENT_MAX_RETRIES = int(os.getenv("AGENT_MAX_RETRIES", "3"))
AGENT_TIMEOUT = int(os.getenv("AGENT_TIMEOUT", "60"))

# 日志配置
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")


def get_config_summary():
    """获取配置摘要（隐藏敏感信息）"""
    return {
        "mysql_url": MYSQL_DB_URL.replace(MYSQL_DB_URL.split('@')[0].split('//')[1], "***") if '@' in MYSQL_DB_URL else MYSQL_DB_URL,
        "milvus_host": MILVUS_HOST,
        "milvus_port": MILVUS_PORT,
        "openai_model": OPENAI_MODEL,
        "openai_embedding_model": OPENAI_EMBEDDING_MODEL,
        "openai_api_key": "已设置" if OPENAI_API_KEY else "未设置",
        "openai_base_url": OPENAI_BASE_URL,
        "max_retries": AGENT_MAX_RETRIES,
        "timeout": AGENT_TIMEOUT,
        "log_level": LOG_LEVEL
    }


def validate_config():
    """验证必要的配置项"""
    errors = []
    
    if not OPENAI_API_KEY:
        errors.append("OPENAI_API_KEY 未设置")
    
    if not MYSQL_DB_URL:
        errors.append("MYSQL_DB_URL 未设置")
    
    if not MILVUS_HOST:
        errors.append("MILVUS_HOST 未设置")
    
    if MILVUS_PORT <= 0 or MILVUS_PORT > 65535:
        errors.append(f"MILVUS_PORT 无效: {MILVUS_PORT}")
    
    if AGENT_MAX_RETRIES < 0:
        errors.append(f"AGENT_MAX_RETRIES 无效: {AGENT_MAX_RETRIES}")
    
    if AGENT_TIMEOUT <= 0:
        errors.append(f"AGENT_TIMEOUT 无效: {AGENT_TIMEOUT}")
    
    return errors


if __name__ == "__main__":
    print("Text2SQL Agent 配置信息:")
    print("=" * 40)
    
    config = get_config_summary()
    for key, value in config.items():
        print(f"{key}: {value}")
    
    print("\n配置验证:")
    errors = validate_config()
    if errors:
        print("❌ 配置错误:")
        for error in errors:
            print(f"  - {error}")
    else:
        print("✅ 配置验证通过")
